using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;

using System.Web.Security;
using Dragon.Prototype1.Infrastructure.Controls;
using Dragon.Prototype1.Infrastructure.FormBuilder;

using Dragon.Prototype1.Service;

namespace Dragon.Prototype1.Web.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/
        [Authorize()]
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ListData(string sidx,string sord,int page,int rows,string userName,string email)
        {
            StringBuilder whereString = new StringBuilder();

            string sortString=null;
            if(string.Compare(sidx,"username",true)==0)
            {
               sortString= string.Format("aspnet_users.{0} {1}", sidx, sord.ToUpper());
            }
            else if (string.Compare(sidx, "email", true) == 0                
                ||string.Compare(sidx,"createdate",true)==0
                ||string.Compare(sidx,"lastlogindate",true)==0)
            {
                sortString = string.Format("aspnet_Membership.{0} {1}", sidx, sord.ToUpper());
            }
            whereString.Append("1=1");
            if (!string.IsNullOrEmpty(userName))
                whereString.AppendFormat(" and aspnet_Users.LoweredUserName like '%{0}%'", userName.ToLower());
            if(!string.IsNullOrEmpty(email))
                whereString.AppendFormat(" and aspnet_Membership.LoweredEmail like '%{0}%'", email.ToLower());
            var users = UserService.GetUsers(page, rows, sortString, whereString.Length == 0 ? null : whereString.ToString());

            int totalnum = users.Count;
            var jsonData = new
            {
                total = totalnum / rows + 1,
                page = page,
                records = totalnum,
                rows = (from row in users
                        select new
                        {
                            id = row.UserId.ToString(),
                            cell = new string[]
                            {
                                row.UserId.ToString(),
                                row.UserName,
                                row.Email,
                                row.CreateDate.ToString("yyyy-MM-dd"),
                                row.LastLoginDate.ToString("yyyy-MM-dd")
                            }
                        }).ToArray()
            };    

            return Json(jsonData);
        }
        public ActionResult Popup(string hide_clear_button,string mode)
        {
            //bool booleanParse;
            ViewData["mode"] = mode;
            return View();
        }

        jQueryFormBuilder CreatePasswordForm()
        {

            jQueryFormBuilder formbuilder = new jQueryFormBuilder();
            formbuilder.CssClass = "tabcontainer";
            FormGroup formgroup1 = new FormGroup("MAINGROUP");
            formgroup1.ColumnNumber = 1;
            formgroup1.Width = "650px";
            formgroup1.AddLabeledPasswordBox("oldPassword", this.Resource("User", "OLDPASSWORD"), true);
            formgroup1.AddLabeledPasswordBox("newPassword", this.Resource("User", "NEWPASSWORD"), true);
            formgroup1.AddLabeledPasswordBox("newPassword2", this.Resource("User", "CONFIRMNEWPASSWORD"), true);
            formbuilder.Groups.Add(formgroup1);
            return formbuilder;
        }
        public ActionResult ChangePassword()
        {

            return View(CreatePasswordForm());
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangePassword(string oldPassword,string newPassword)
        {
            if (Membership.Provider.ChangePassword(this.User.Identity.Name, oldPassword, newPassword))
            {
                return this.RedirectToAction("ChangePasswordSuccess");
            }
            ViewData["ErrorMessage"] = this.Resource("User","MSG_CHANGEPASSWORDFAILED");
            return View(CreatePasswordForm());
        }
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult Login()
        {
            string returnurl = this.Request.QueryString["ReturnUrl"];
            ViewData["returnURL"] = returnurl;
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string userName, string pwd, string returnURL)
        {
            //string returnURL = string.Empty;
            if (Membership.ValidateUser(userName, pwd))
            {
                FormsAuthentication.SetAuthCookie(userName,true);
                UserProfile.SaveUserId(userName);

                
                if (string.IsNullOrEmpty(returnURL))
                {
                    return this.RedirectToAction("Index", "Home");
                }
                else
                {
                    return this.Redirect(returnURL);
                }
            }
            else
            {
                MembershipUser user=Membership.GetUser(userName);
                //string querystring="?q=1";
                if (user!=null)
                {
                    if (user.IsLockedOut == true)
                    {
                        ViewData["ErrorMessage"] = this.Resource("User","MSG_USERLOCKED");
                    }
                }
                ViewData["returnUrl"] = returnURL;

                if(ViewData["ErrorMessage"]==null)
                    ViewData["ErrorMessage"] =this.Resource("User","MSG_INCORRECT_USERNAME_PWD");
                return View();
            }
        }
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Login", "User");
        }


        //
        // GET: /User/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /User/Create

        private jQueryFormBuilder CreateForm()
        {
            jQueryFormBuilder formbuilder = new jQueryFormBuilder();
            formbuilder.CssClass = "tabcontainer";
            FormGroup formgroup1 = new FormGroup("BASICINFO");
            formgroup1.ColumnNumber = 2;
            formgroup1.Width = "100%";
            formgroup1.AddLabeledTextBox("userName",this.Resource("User","USERNAME"), true);
            formgroup1.AddLabeledTextBox("email", this.Resource("User", "Email"), true);
            formgroup1.AddLabeledPasswordBox("password1", this.Resource("User", "PASSWORD"), true);
            formgroup1.AddLabeledPasswordBox("password2", this.Resource("User", "CONFIRMPASSWORD"), true);
            formbuilder.Groups.Add(formgroup1);

            FormGroup formgroup2 = new FormGroup("PASSWORDRECOVERYINFO");
            formgroup2.AddLabeledTextBox("pwdQuestion", this.Resource("User", "PASSWORDQUESTION"), false, true);
            formgroup2.AddLabeledTextBox("pwdAnswer", this.Resource("User", "PASSWORDANSWER"), false, true);
            formbuilder.Groups.Add(formgroup2);

            //get roles
            string[] roles = Roles.GetAllRoles();
            List<string> labels = new List<string>();
            foreach (string rolename in roles)
            {
                labels.Add(rolename);
            }

            FormGroup formgroup3 = new FormGroup("ROLES");
            formgroup3.AddLabeledCheckboxList("roles", this.Resource("User", "ROLES"), labels, labels, null, true, true);
            formbuilder.Groups.Add(formgroup3);
            return formbuilder;
        }

        public ActionResult Create()
        {
            
            return View(CreateForm());
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(string userName, string password1, string email, string pwdQuestion, string pwdAnswer,string oper,string id,string[] roles)
        {
            if (oper == "edit")
            {
                MembershipUser user = Membership.GetUser(new Guid(id));
                if (user == null)
                    throw new InvalidOperationException("Save failed");
                
                user.Email = email;
                Membership.UpdateUser(user);
            }
            else 
            {
                    MembershipUser newUser=null;
                    if (string.IsNullOrEmpty(pwdQuestion) || string.IsNullOrEmpty(pwdAnswer))
                    {
                        try
                        {
                            newUser=Membership.CreateUser(userName, password1, email);
                        }
                        catch (MembershipCreateUserException e)
                        {
                            ViewData["ErrorMessage"] = e.Message;
                            return View("Create", CreateForm());
                        }
                    }
                    else
                    {
                        MembershipCreateStatus mc;
                        newUser=Membership.CreateUser(userName, password1, email, pwdQuestion, pwdAnswer, true, out mc);
                        if (mc != MembershipCreateStatus.Success)
                        {
                            switch (mc)
                            {
                                case MembershipCreateStatus.DuplicateUserName:
                                    ViewData["ErrorMessage"] = "Username already exists. Please enter a different user name.";
                                    break;
                                case MembershipCreateStatus.DuplicateEmail:
                                    ViewData["ErrorMessage"] = "A username for that e-mail address already exists. Please enter a different e-mail address.";
                                    break;
                                case MembershipCreateStatus.InvalidPassword:
                                    ViewData["ErrorMessage"] = "The password provided is invalid. Please enter a valid password value.";
                                    break;
                                case MembershipCreateStatus.InvalidEmail:
                                    ViewData["ErrorMessage"] = "The e-mail address provided is invalid. Please check the value and try again.";
                                    break;
                                case MembershipCreateStatus.InvalidAnswer:
                                    ViewData["ErrorMessage"] = "The password retrieval answer provided is invalid. Please check the value and try again.";
                                    break;
                                case MembershipCreateStatus.InvalidQuestion:
                                    ViewData["ErrorMessage"] = "The password retrieval question provided is invalid. Please check the value and try again.";
                                    break;
                                case MembershipCreateStatus.InvalidUserName:
                                    ViewData["ErrorMessage"] = "The user name provided is invalid. Please check the value and try again.";
                                    break;
                                case MembershipCreateStatus.UserRejected:
                                    ViewData["ErrorMessage"] = "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
                                    break;
                                default:
                                    ViewData["ErrorMessage"] = "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
                                    break;
                            }
                            return View("Create", CreateForm());
                        }
                    }
                    if (roles.Length > 0)
                    {
                        Roles.AddUserToRoles(userName, roles);
                    }
                    DepartmentService.SetUnassignedUser((Guid)newUser.ProviderUserKey);
            }
            
            return RedirectToAction("Index","User");
        }

        //
        // GET: /User/Edit/5
        public ActionResult Edit(Guid id)
        {
            if (id == Guid.Empty)
            {
                return RedirectToAction("Index");
            }

            ViewData["id"] = id.ToString();
            MembershipUser user=Membership.GetUser(id);
            
            jQueryFormBuilder formbuilder = new jQueryFormBuilder();
            formbuilder.CssClass = "tabcontainer";
            FormGroup formgroup1 = new FormGroup("BASICINFO");
            formgroup1.ColumnNumber = 2;
            formgroup1.Width = "100%";
            formgroup1.AddLabeledTextBox("userName", this.Resource("User", "USERNAME"), user.UserName, true);
            formgroup1.AddLabeledTextBox("email", this.Resource("User", "EMAIL"), user.Email, true);
            formbuilder.Groups.Add(formgroup1);

            //get roles
            string[] roles = Roles.GetAllRoles();
            string[] rolesForUser = Roles.GetRolesForUser(user.UserName);

            List<string> labels = new List<string>();
            List<bool> checkedlist = new List<bool>();
            foreach (string rolename in roles)
            {
                labels.Add(rolename);
                bool rolefound = false;
                foreach (string userrole in rolesForUser)
                {
                    if (userrole == rolename)
                    {
                        checkedlist.Add(true);
                        rolefound = true;
                        break;
                    }
                }
                if (!rolefound)
                {
                    checkedlist.Add(false);
                }
            }

            FormGroup formgroup3 = new FormGroup("ROLES");
            formgroup3.AddLabeledCheckboxList("roles", this.Resource("User", "ROLES"), labels, labels, checkedlist, true, true);
            formbuilder.Groups.Add(formgroup3);
            return View(formbuilder);
        }

        //
        // POST: /User/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(string id,string oper,FormCollection collection)
        {               
               if (oper == "del")
               {
                   string[] ids = id.Split(new char[] { ',' });
                   foreach(string i in ids)
                   {
                       if (Membership.DeleteUser(i) == false)
                           throw new InvalidOperationException("delete user failed");                    
                   }
               }
               return Json(true);
        }
    }
}
